//add by owen 修复 path 无法引用http://页面的问题 begin
String.prototype.startWith = function (str) {
    if (str == null || str == "" || this.length == 0
        || str.length > this.length)
        return false;
    if (this.substr(0, str.length) == str)
        return true;
    else
        return false;
    return true;
}


function initIFrame() {
    var $parent = $(".admin-iframe").parent();
    if ($parent.hasClass('layui-body')) {
        $parent.addClass('admin-iframe-body');
        return;
    }
    if ($parent.hasClass('layui-tab-item')) {
        $parent.css({'padding': '0', 'overflow-y': 'hidden'});
    } else {
        $parent.css({'width': '100%', 'height': '100%'});
    }
}

//add by owen 修复 path 无法引用http://页面的问题 end

layui.define(['config', 'admin', 'layer', 'laytpl', 'element', 'form', '_user', 'tools'], function (exports) {
    var $ = layui.$;
    var config = layui.config;
    var admin = layui.admin;
    var layer = layui.layer;
    var laytpl = layui.laytpl;
    var element = layui.element;
    var form = layui.form;
    var _user = layui._user;
    var tools = layui.tools;
    var index = {
        // 渲染左侧菜单栏
        initLeftNav: function () {
            tools.request({
                url: '/plm/api/menu?simpleCode=' + config.simpleCode,
                method: 'get'
            }).done(function (res) {
                if (res.code == 0) {
                    var rp = tools.parseData(res);
                    var data = rp.data;
                    tools.putTempData("menus", data.menus);
                    tools.putTempData("clientList", data.clientList);
                    var menus = data.menus || [];
                    // 判断权限
                    for (var i = menus.length - 1; i >= 0; i--) {
                        var tempMenu = menus[i];
                        if (tempMenu.auth && !admin.hasPerm(tempMenu.auth)) {
                            menus.splice(i, 1);
                            continue;
                        }
                        if (!tempMenu.children) {
                            continue;
                        }
                        for (var j = tempMenu.children.length - 1; j >= 0; j--) {
                            var jMenus = tempMenu.children[j];
                            if (jMenus.auth && !admin.hasPerm(jMenus.auth)) {
                                tempMenu.children.splice(j, 1);
                                continue;
                            }
                            if (!jMenus.children) {
                                continue;
                            }
                            for (var k = jMenus.children.length - 1; k >= 0; k--) {
                                if (jMenus.children[k].auth && !admin.hasPerm(jMenus.children[k].auth)) {
                                    jMenus.children.splice(k, 1);
                                    continue;
                                }
                            }
                        }
                    }
                    // 去除空的目录
                    for (var i = menus.length - 1; i >= 0; i--) {
                        var tempMenu = menus[i];
                        if (!tempMenu.children) {
                            continue;
                        }
                        for (var j = tempMenu.children.length - 1; j >= 0; j--) {
                            var jMenus = tempMenu.children[j];
                            if (jMenus.children && jMenus.children.length <= 0) {
                                jMenus.children.splice(j, 1);
                                continue;
                            }
                        }
                    }
                    // 渲染
                    $('.layui-layout-admin .layui-side').load('public/pages/side.html?v=' + config.version, function () {
                        laytpl(sideNav.innerHTML).render({
                            "menus": menus,
                            "systemName": config.systemName
                        }, function (html) {
                            $('#sideNav').after(html);
                        });
                        element.render('nav');
                        admin.activeNav(Q.lash);
                    });
                    index.initRouter();
                } else {

                }
            })
        },
        // 路由注册
        initRouter: function () {
            index.regRouter(tools.getTempData("menus"));
            // index.regRouter(config.menus);
            Q.reg('index', function () {
                var menuPath = 'pages/index.html?v=' + config.version
                index.loadView('index', menuPath, '主页');
            });
            //首页注册
            Q.init({
                index: 'index'
            });
        },
        // 使用递归循环注册
        regRouter: function (menus) {
            $.each(menus, function (i, data) {
                if (data.url && data.url.indexOf('#!') == 0) {
                    Q.reg(data.url.substring(2), function () {
                        let flag = data.path.startWith("http://");
                        //临时保存url
                        flag ? tools.putTempData("params", data.path) : null;

                        var menuId = data.url.substring(2);
                        //1.add by owen 修复 path 无法引用http://页面的问题
                        //2.加/引入公共部分的页面
                        let path = data.path + '';
                        if (path.indexOf('/') == 0) {
                            path = "public/pages" + path;
                        } else if (path.indexOf('|') == 0) {
                            ;//不变动，原样请求
                        } else {
                            path = 'pages/' + path;
                        }
                        var menuPath = flag ? 'public/pages/tpl/iframe.html' : path;
                        index.loadView(menuId, menuPath, data.name);
                    });
                }
                if (data.children) {
                    index.regRouter(data.children);
                }
            });
        },
        // 路由加载组件
        loadView: function (menuId, menuPath, menuName) {
            var contentDom = '.layui-layout-admin .layui-body';
            admin.showLoading('.layui-layout-admin .layui-body');
            var flag;  // 选项卡是否添加
            flag = menuPath.startWith("http://") ? false : flag;
            // 判断是否开启了选项卡功能
            if (config.pageTabs) {
                $('.layui-layout-admin .layui-body .layui-tab .layui-tab-title>li').each(function (index) {
                    if ($(this).attr('lay-id') === menuId) {
                        flag = true;
                    }
                });
                if (!flag) {
                    element.tabAdd('admin-pagetabs', {
                        title: menuName,
                        //add by owen 修复 path 无法引用http://页面的问题
                        content: menuPath.startWith("http://") ? '<div id="admin-iframe" style="width: 100%; height: 100%;"><iframe id="' + menuId + '" src="' + menuPath + '" marginwidth="0"  marginheight="0" width="100%" height="100%"  frameborder="0" onload="initIFrame()"></iframe> </div>' : '<div id="' + menuId + '"></div>',
                        id: menuId
                    });
                }
                contentDom = '#' + menuId;
                element.tabChange('admin-pagetabs', menuId);
                admin.rollPage('auto');
                // 切换tab关闭表格内浮窗
                $('.layui-table-tips-c').trigger('click');
                // 解决切换tab滚动条时而消失的问题
                var $iframe = $('.layui-layout-admin .layui-body .layui-tab-content .layui-tab-item.layui-show .admin-iframe')[0];
                if ($iframe) {
                    $iframe.style.height = "99%";
                    $iframe.scrollWidth;
                    $iframe.style.height = "100%";
                }
            }
            if (!flag || admin.isRefresh) {
                $(contentDom).load(menuPath, function () {
                    admin.isRefresh = false;
                    element.render('breadcrumb');
                    form.render('select');
                    admin.removeLoading('.layui-layout-admin .layui-body');
                });
            } else {
                admin.removeLoading('.layui-layout-admin .layui-body');
            }
            admin.activeNav(Q.lash);
            // 移动设备切换页面隐藏侧导航
            if (document.body.clientWidth <= 750) {
                admin.flexible(true);
            }
        },
        // 从服务器获取登录用户的信息
        getUser: function (success) {
            layer.load(2);
            _user.getUserInfo().done(function (res) {
                layer.closeAll('loading');
                if (0 == res.code) {
                    const data = res.data || {}
                    config.putUser({userInfo: data.sysUser, "roles": data.roles, permissions: data.permissions});
                    success(data.sysUser);
                } else {
                    layer.msg('获取用户失败', {icon: 2});
                    //add by owen 登录失败重定向到登录页
                    _user.removeToken();
                    location.replace('login.html');
                    return;
                }
            })
        },
        // 页面元素绑定事件监听
        bindEvent: function () {
            // 退出登录
            $('#btnLogout').click(function () {
                layer.confirm('确定退出登录？', function () {
                    _user.logout().done(function (data) {
                        config.removeToken();
                        location.replace('login.html');
                    })
                });
            });
            // 修改密码
            $('#setInfo').click(function () {
                tools.goto('/account/#!basic')
            });
            // 个人信息
            $('#setSecurity').click(function () {
                tools.goto('/account/#!security')
            });
            // 消息
            $('#btnMessage').click(function () {
                admin.popupRight('public/pages/tpl/message.html?v=' + config.version);
            });
        },
        // 打开新页面
        openNewTab: function (param) {
            var url = param.url;
            var title = param.title;
            var menuId = param.menuId;
            if (!menuId) {
                menuId = url.replace(/[?:=&/]/g, '_');
            }
            index.loadView(menuId, url, title);
        },
        // 关闭选项卡
        closeTab: function (menuId) {
            element.tabDelete('admin-pagetabs', menuId);
        }
    };

    // tab选项卡切换监听
    element.on('tab(admin-pagetabs)', function (data) {
        var layId = $(this).attr('lay-id');
        Q.go(layId);
    });

    exports('index', index);
});
